package com.axzhengxin.platform.sync.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.axzhengxin.platform.business.domain.BizApproveInfo;
import com.axzhengxin.platform.business.domain.BizFlowInfo;
import com.axzhengxin.platform.business.mapper.BizFlowInfoMapper;
import com.axzhengxin.platform.sync.ISyncDataService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ApproveBizFlowSyncServiceImpl
 *
 * @author jiangnan
 * @date 2021/4/6
 */
@Slf4j
@Service
public class ApproveBizFlowSyncServiceImpl implements ISyncDataService {

    @Autowired
    private BizFlowInfoMapper bizFlowInfoMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private DataSource ecscDs;

    @SneakyThrows
    @Override
    public void exec() {
        Map<String, String> userDeptMapper = loadUserDeptMapper();
        Db.use(ecscDs)
                .find(Entity.create("biz_approve_info"), BizApproveInfo.class)
                .stream()
                .map(approve -> {
                    BizFlowInfo bizFlowInfo = new BizFlowInfo();
                    bizFlowInfo.setBizId(approve.getApplyId());
                    bizFlowInfo.setBizType("APPROVE");
                    bizFlowInfo.setCurrentNodeUserId(approve.getCreateBy());
                    bizFlowInfo.setCurrentNodeDeptId(userDeptMapper.get(approve.getCreateBy()));
                    bizFlowInfo.setStatus(2000);
                    bizFlowInfo.setCreateBy(approve.getCreateBy());
                    bizFlowInfo.setCreateTime(approve.getCreateTime());
                    return bizFlowInfo;
                })
                .forEach(bizFlowInfo -> bizFlowInfoMapper.insertBizFlowInfo(bizFlowInfo));

    }

    @Override
    public int getOrder() {
        return BizApproveInfoSyncServiceImpl.ORDER + 1;
    }

    private Map<String, String> loadUserDeptMapper() {
        return sysUserMapper.selectUserList(new SysUser())
                .stream()
                .collect(Collectors.toMap(user -> String.valueOf(user.getUserId()),
                        user -> String.valueOf(user.getDeptId())));
    }

}
